import axios from "axios";
// 轻提示
export function toast(info = {}, navigateOpt) {
	let title = info.title || "";
	let icon = info.icon || "none";
	let endtime = info.endtime || 2000;
	if (title)
		uni.showToast({
			title: title,
			icon: icon,
			duration: endtime,
		});
	if (navigateOpt != undefined) {
		if (typeof navigateOpt == "object") {
			let tab = navigateOpt.tab || 1,
				url = navigateOpt.url || "";
			switch (tab) {
				case 1:
					//跳转至 table
					setTimeout(function() {
						uni.switchTab({
							url: url,
						});
					}, endtime);
					break;
				case 2:
					//跳转至非table页面
					setTimeout(function() {
						uni.navigateTo({
							url: url,
						});
					}, endtime);
					break;
				case 3:
					//返回上页面
					setTimeout(function() {
						uni.navigateBack({
							delta: parseInt(url),
						});
					}, endtime);
					break;
				case 4:
					//关闭当前所有页面跳转至非table页面
					setTimeout(function() {
						uni.reLaunch({
							url: url,
						});
					}, endtime);
					break;
				case 5:
					//关闭当前页面跳转至非table页面
					setTimeout(function() {
						uni.redirectTo({
							url: url,
						});
					}, endtime);
					break;
			}
		} else if (typeof navigateOpt == "function") {
			setTimeout(function() {
				navigateOpt && navigateOpt();
			}, endtime);
		}
	}
}

//当前页面
export function currentPage() {
	let pages = getCurrentPages();
	let currentPage = pages[pages.length - 1];
	return currentPage || {};
}

//节流
export const trottle = (func, time = 1000, context) => {
	let previous = new Date(0).getTime();
	return function(...args) {
		let now = new Date().getTime();
		if (now - previous > time) {
			func.apply(context, args);
			previous = now;
		}
	};
};

//计算年龄
export function calculateAge(birthDateString) {
	// 将出生日期字符串转换为Date对象
	const birthDate = new Date(birthDateString);
	// 获取当前日期
	const currentDate = new Date();

	let age = currentDate.getFullYear() - birthDate.getFullYear();
	const monthDifference = currentDate.getMonth() - birthDate.getMonth();
	const dateDifference = currentDate.getDate() - birthDate.getDate();

	// 如果当前月份小于出生月份，或者当前月份等于出生月份但今天的日期小于出生日期，则年龄减一
	if (monthDifference < 0 || (monthDifference === 0 && dateDifference < 0)) {
		age--;
	}

	return age;
}

/**
 * 使用 AK，SK 生成鉴权签名（Access Token）
 * @return string 鉴权签名信息（Access Token）
 */
const AK = "yhrUSJ9Cg87atgumSNrNmNEh";
const SK = "5Im88qdmtLS07eea2pNwnwrTPYuO2jFU";

export function getAccessToken() {
    return new Promise((resolve, reject) => {
        uni.request({
            url: 'https://aip.baidubce.com/oauth/2.0/token',
            method: 'POST',
            data: {
                grant_type: 'client_credentials',
                client_id: AK,
                client_secret: SK
            },
            success: (res) => {
                if (res.statusCode === 200) {
                    resolve(res.data.access_token);
                } else {
                    reject(new Error('Failed to fetch access token'));
                }
            },
            fail: (err) => {
                reject(err);
            }
        });
    });
}